#!/bin/bash

# 备份脚本 - Ubuntu 24.04
# 用法: ./backup-ubuntu.sh

BACKUP_DIR="/var/backups/web-notes"
DATE=$(date +%Y%m%d_%H%M%S)

echo "🔄 开始备份 Web Notes 应用..."

# 颜色定义
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# 创建备份目录
sudo mkdir -p $BACKUP_DIR
sudo chown $USER:$USER $BACKUP_DIR

echo -e "${YELLOW}备份数据库...${NC}"

# 备份 MongoDB 数据 (使用认证)
if mongosh --quiet --eval "db.runCommand('ismaster')" > /dev/null 2>&1; then
    # 无认证备份
    mongodump --db web-notes-prod --out $BACKUP_DIR/mongodb_$DATE
else
    # 有认证备份
    mongodump --host localhost:27017 \
              --username webnotesuser \
              --password 'WebNotes@App2024!' \
              --authenticationDatabase web-notes-prod \
              --db web-notes-prod \
              --out $BACKUP_DIR/mongodb_$DATE
fi

echo -e "${YELLOW}备份上传文件...${NC}"

# 备份上传文件
if [ -d "/var/www/web-notes/web-notes-backend/uploads" ]; then
    tar -czf $BACKUP_DIR/uploads_$DATE.tar.gz -C /var/www/web-notes/web-notes-backend uploads
else
    echo "上传目录不存在，跳过..."
fi

echo -e "${YELLOW}备份配置文件...${NC}"

# 备份配置文件
mkdir -p $BACKUP_DIR/config_$DATE
cp /var/www/web-notes/web-notes-backend/.env $BACKUP_DIR/config_$DATE/ 2>/dev/null || echo "后端配置文件不存在"
cp /etc/nginx/sites-available/web-notes $BACKUP_DIR/config_$DATE/ 2>/dev/null || echo "Nginx配置文件不存在"
cp /var/www/web-notes/ecosystem.config.json $BACKUP_DIR/config_$DATE/ 2>/dev/null || echo "PM2配置文件不存在"
cp /etc/mongod.conf $BACKUP_DIR/config_$DATE/ 2>/dev/null || echo "MongoDB配置文件不存在"

echo -e "${YELLOW}清理旧备份...${NC}"

# 清理旧备份 (保留7天)
find $BACKUP_DIR -type d -name "mongodb_*" -mtime +7 -exec rm -rf {} \; 2>/dev/null || true
find $BACKUP_DIR -type d -name "config_*" -mtime +7 -exec rm -rf {} \; 2>/dev/null || true
find $BACKUP_DIR -name "uploads_*.tar.gz" -mtime +7 -delete 2>/dev/null || true

echo -e "${GREEN}备份完成！${NC}"
echo -e "\n备份位置: ${YELLOW}$BACKUP_DIR${NC}"
echo -e "\n备份文件:"
ls -la $BACKUP_DIR/

echo -e "\n${YELLOW}恢复命令示例:${NC}"
echo -e "恢复数据库: ${YELLOW}mongorestore --db web-notes-prod $BACKUP_DIR/mongodb_$DATE/web-notes-prod${NC}"
echo -e "恢复文件: ${YELLOW}tar -xzf $BACKUP_DIR/uploads_$DATE.tar.gz -C /var/www/web-notes/web-notes-backend/${NC}"